package csel.controller.bindings;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Enumeration;
import java.util.HashMap;

import csel.controller.enums.ActionEnum;

public class BindingModifier implements Bindable
{
	private final KeyBindings keyBindings;
	private final HashMap<String, ActionEnum> stringMappings;
	
	public BindingModifier(KeyBindings keyBindings)
	{
		this.keyBindings = keyBindings;
		this.stringMappings = new HashMap<String, ActionEnum>();
		Enumeration<ActionEnum> actions = keyBindings.getValues();
		while( actions.hasMoreElements() )
		{
			ActionEnum ae = actions.nextElement();
			stringMappings.put("" + ae, ae);
		}
	}
	 
	/**
	 * ========================================================================
	 * changeBinding() -- changes a binding in the pool, erases the old
	 */
	public void changeBinding(Integer virtualKey, ActionEnum actionEnum)
	{
		keyBindings.remove( actionEnum );
		keyBindings.updateBinding( virtualKey, actionEnum );
	}

	/**
	 * ========================================================================
	 * saveBindings() -- saves the bindings to a file in the specified filename
	 */
	public void saveBindings(String fileName) throws IOException
	{
		FileWriter fw = new FileWriter(fileName);
		Writer output = new BufferedWriter(fw);
		Enumeration<Integer> keyList = keyBindings.getKeys();
		while( keyList.hasMoreElements() )
		{
			Integer virtualKey = keyList.nextElement();
			String keyValuePair = "" + virtualKey + ","
					+ keyBindings.getEnum(virtualKey) + "\n";
			output.write(keyValuePair);
		}
		output.close();
	}
	
	/**
	 * ========================================================================
	 * loadBindings() -- saves the bindings to a file in the specified filename
	 */
	public void loadBindings(String fileName) throws IOException
	{
		FileReader reader = new FileReader(fileName);
		BufferedReader input = new BufferedReader(reader);
		String item;
		while( (item = input.readLine()) != null )
		{
			String[] keyValPair = item.split(",");
			Integer k = Integer.parseInt(keyValPair[0]);
			ActionEnum v = stringMappings.get(keyValPair[1]);
			changeBinding( k, v );
		}
	}
}
